<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceKey">
              <el-input v-model="queryParams.deviceKey" placeholder="请输入设备编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备分组" prop="groupIds">
              <el-select v-model="form.deviceType" placeholder="请选择设备分组" clearable>
                <el-option v-for="dict in iot_device_group" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属空间" prop="roomId">
              <el-select v-model="queryParams.roomId" placeholder="请选择所属空间" clearable>
                <el-option v-for="item in roomDeatails" :key="item.id" :label="item.teroomName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备类型" prop="groupIds">
              <el-select v-model="form.deviceType" placeholder="请选择设备类型" clearable>
                <el-option v-for="dict in iot_device_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="float-right !mr-0 !mb-0">
              <el-button-group>
                <el-button icon="grid" :type="viewMode === 'card' ? 'primary' : 'default'" @click="viewMode = 'card'"> </el-button>
                <el-button icon="list" :type="viewMode === 'list' ? 'primary' : 'default'" @click="viewMode = 'list'"> </el-button>
              </el-button-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 列表 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['tearoom:iotDevice:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['tearoom:iotDevice:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['tearoom:iotDevice:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['tearoom:iotDevice:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <template v-if="viewMode === 'card'">
        <el-row :gutter="16" v-if="iotDeviceList.length > 0">
          <el-col v-for="item in iotDeviceList" :key="item.id" :xs="24" :sm="12" :md="12" :lg="6" class="mb-4">
            <el-card class="h-full transition-colors relative overflow-hidden" :body-style="{ padding: '0' }">
              <!-- 添加渐变背景层 -->
              <div
                class="absolute top-0 left-0 right-0 h-[50px] pointer-events-none"
                :class="[
                  item.state == DeviceStateEnum.ONLINE
                    ? 'bg-gradient-to-b from-[#cef7d7] to-transparent'
                    : 'bg-gradient-to-b from-[#fff1f1] to-transparent'
                ]"
              ></div>
              <div class="p-4 relative">
                <!-- 标题区域 -->
                <div class="flex items-center mb-3">
                  <div class="mr-2.5 flex items-center">
                    <el-image :src="defaultIconUrl" class="w-[18px] h-[18px]" />
                  </div>
                  <div class="text-[16px] font-600 flex-1">{{ item.deviceName }}</div>
                  <!-- 添加设备状态标签 -->
                  <div class="inline-flex items-center">
                    <div
                      class="w-1 h-1 rounded-full mr-1.5"
                      :class="item.state === DeviceStateEnum.ONLINE ? 'bg-[var(--el-color-success)]' : 'bg-[var(--el-color-danger)]'"
                    ></div>
                    <el-text class="!text-xs font-bold" :type="item.state === DeviceStateEnum.ONLINE ? 'success' : 'danger'">
                      {{ getDictLabel(iot_device_state, item.state) }}
                    </el-text>
                  </div>
                </div>

                <!-- 信息区域 -->
                <div class="flex items-center text-[14px]">
                  <div class="flex-1">
                    <div class="mb-2.5 last:mb-0">
                      <span class="text-[#717c8e] mr-2.5">所属空间</span>
                      <span class="text-[#0070ff]">
                        {{ roomDeatails.find((r) => r.id === item.roomId)?.teroomName }}
                      </span>
                    </div>
                    <div class="mb-2.5 last:mb-0" style="display: flex">
                      <span class="text-[#717c8e] mr-2.5">设备类型</span>
                      <dict-tag :options="iot_device_type" :value="item.deviceType" />
                    </div>
                    <div class="mb-2.5 last:mb-0" style="display: flex">
                      <span class="text-[#717c8e] mr-2.5">设备种类</span>
                      <dict-tag :options="iot_device_class" :value="item.deviceClass" />
                    </div>
                    <div class="mb-2.5 last:mb-0">
                      <span class="text-[#717c8e] mr-2.5">设备编号</span>
                      <span class="text-[#0b1d30] inline-block align-middle overflow-hidden text-ellipsis whitespace-nowrap max-w-[130px]">
                        {{ item.deviceKey }}
                      </span>
                    </div>
                    <div class="mb-2.5 last:mb-0">
                      <span class="text-[#717c8e] mr-2.5">开关状态</span>
                      <el-switch v-model="item.keyStatus" :active-value="1" :inactive-value="0" @change="handleStatusChange(item)"></el-switch>
                    </div>
                  </div>
                  <div class="w-[100px] h-[100px]">
                    <el-image :src="item.picUrlUrl" class="w-full h-full" v-if="item.picUrlUrl" />
                    <el-image :src="defaultPicUrl" class="w-full h-full" v-else />
                  </div>
                </div>

                <!-- 分隔线 -->
                <el-divider class="!my-3" />

                <!-- 按钮 -->
                <div class="flex items-center px-0">
                  <el-button
                    class="flex-1 !px-2 !h-[32px] text-[13px]"
                    type="primary"
                    plain
                    @click="handleUpdate(item)"
                    icon="edit"
                    v-hasPermi="['tearoom:iotDevice:edit']"
                  >
                    编辑
                  </el-button>
                  <!-- <el-button icon="view" class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]" type="warning" plain @click="handleUpdate()">
                    详情
                  </el-button> -->
                  <el-button class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]" type="info" plain icon="tickets"  @click="handleLog(item)">日志</el-button>
                  <div class="mx-[10px] h-[20px] w-[1px] bg-[#dcdfe6]"></div>
                  <el-button
                    class="!px-2 !h-[32px] text-[13px]"
                    type="danger"
                    plain
                    @click="handleDelete(item)"
                    icon="delete"
                    v-hasPermi="['tearoom:iotDevice:remove']"
                  >
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <template v-else>
          <el-empty description="没有数据~" />
        </template>
      </template>

      <el-table v-loading="loading" :data="iotDeviceList" @selection-change="handleSelectionChange" v-else>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备图片" align="center" prop="picUrlUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.picUrlUrl" :width="50" :height="50" v-if="scope.row.picUrlUrl" />
            <image-preview :src="defaultPicUrl" :width="50" :height="50" v-else />
          </template>
        </el-table-column>
        <el-table-column label="所属空间" align="center" prop="roomId">
          <template #default="scope">
            {{ roomDeatails.find((r) => r.id === scope.row.roomId)?.teroomName }}
          </template>
        </el-table-column>
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="备注名称" align="center" prop="nickname" />
        <el-table-column label="设备编号" align="center" prop="deviceKey" width="140px" />
        <!-- <el-table-column label="设备序列号" align="center" prop="serialNumber" /> -->
        <el-table-column label="设备类型" align="center" prop="deviceType">
          <template #default="scope">
            <dict-tag :options="iot_device_type" :value="scope.row.deviceType" />
          </template>
        </el-table-column>
        <el-table-column label="设备种类" align="center" prop="deviceClass">
          <template #default="scope">
            <dict-tag :options="iot_device_class" :value="scope.row.deviceClass" />
          </template>
        </el-table-column>
        <el-table-column label="所属分组" align="center" prop="groupIds">
          <template #default="scope">
            <dict-tag :options="iot_device_group" :value="scope.row.groupIds" />
          </template>
        </el-table-column>
        <el-table-column label="设备状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="iot_device_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="开关状态" align="center" prop="state">
          <template #default="scope">
            <el-switch v-model="scope.row.keyStatus" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="最后上线时间" align="center" prop="onlineTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.onlineTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tearoom:iotDevice:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="日志" placement="top">
              <el-button link type="primary" icon="List" @click="handleLog(scope.row)" v-hasPermi="['tearoom:iotDevice:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tearoom:iotDevice:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改IoT设备对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="iotDeviceFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="空间" prop="roomId">
          <el-select v-model="form.roomId" placeholder="请选择空间" clearable>
            <el-option v-for="room in roomDeatails" :key="room.id" :label="room.teroomName" :value="room.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceKey">
          <el-input v-model="form.deviceKey" placeholder="请输入设备编号">
            <!-- <template #append>
              <el-button @click="generateDeviceKey" :disabled="formType === 'update'"> 重新生成 </el-button>
            </template> -->
          </el-input>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" clearable>
            <el-option v-for="dict in iot_device_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备种类" prop="deviceClass">
          <el-select v-model="form.deviceClass" placeholder="请选择设备种类" clearable>
            <el-option v-for="dict in iot_device_class" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订阅主题" prop="deviceName">
          <el-input v-model="form.mqttSubscribe" placeholder="请输入订阅主题" />
        </el-form-item>
        <el-form-item label="发布主题" prop="deviceName">
          <el-input v-model="form.mqttPublish" placeholder="请输入发布主题" />
        </el-form-item>
        <!-- <el-form-item v-if="form.deviceType === DeviceTypeEnum.GATEWAY_SUB" label="网关设备" prop="gatewayId">
          <el-select v-model="form.gatewayId" placeholder="子设备可选择父设备" clearable>
            <el-option v-for="gateway in gatewayDevices" :key="gateway.id" :label="gateway.nickname || gateway.deviceName" :value="gateway.id" />
          </el-select>
        </el-form-item> -->

        <el-collapse>
          <el-collapse-item title="更多配置">
            <el-form-item label="备注名称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入备注名称" />
            </el-form-item>
            <el-form-item label="设备图片" prop="picUrl">
              <image-upload v-model="form.picUrl" :limit="1" />
            </el-form-item>
            <el-form-item label="设备分组" prop="groupIds">
              <el-select v-model="form.groupIds" placeholder="请选择设备分组" clearable>
                <el-option v-for="dict in iot_device_group" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备序列号" prop="serialNumber">
              <el-input v-model="form.serialNumber" placeholder="请输入设备序列号" />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="IotDevice" lang="ts">
import {
  listIotDevice,
  getIotDevice,
  delIotDevice,
  addIotDevice,
  updateIotDevice,
  changeotDeviceStatus,
  DeviceStateEnum,
  DeviceTypeEnum
} from '@/api/tearoom/iotDevice/index';
import { RoomDetailsVO } from '@/api/tearoom/roomDetails/types';
import { listRoomDetails } from '@/api/tearoom/roomDetails/index';
import { IotDeviceVO, IotDeviceQuery, IotDeviceForm } from '@/api/tearoom/iotDevice/types';

import defaultPicUrl from '@/assets/images/iot/device.png'; // 默认设备图片
import defaultIconUrl from '@/assets/images/iot/card-fill.svg'; // 默认设备图标

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_device_type, iot_device_group, iot_device_state, iot_device_class } = toRefs<any>(
  proxy?.useDict('iot_device_type', 'iot_device_group', 'iot_device_state', 'iot_device_class')
);

const iotDeviceList = ref<IotDeviceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const viewMode = ref<'card' | 'list'>('card'); // 视图模式状态

const queryFormRef = ref<ElFormInstance>();
const iotDeviceFormRef = ref<ElFormInstance>();
const roomDeatails = ref<RoomDetailsVO[]>([]); //茶室列表

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: IotDeviceForm = {
  id: undefined,
  deviceKey: undefined,
  deviceName: undefined,
  nickname: undefined,
  serialNumber: undefined,
  picUrl: undefined,
  groupIds: undefined,
  roomId: undefined,
  productKey: undefined,
  deviceType: undefined,
  deviceClass: undefined,
  gatewayId: undefined,
  state: undefined,
  keyStatus: undefined,
  wifiLock: undefined,
  keyLock: undefined,
  ssid: undefined,
  onlineTime: undefined,
  offlineTime: undefined,
  activeTime: undefined,
  ip: undefined,
  firmwareId: undefined,
  deviceSecret: undefined,
  mqttClientId: undefined,
  mqttUsername: undefined,
  mqttPassword: undefined,
  authType: undefined,
  latitude: undefined,
  longitude: undefined,
  areaId: undefined,
  address: undefined,
  config: undefined,
  remark: undefined
};
const data = reactive<PageData<IotDeviceForm, IotDeviceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceKey: undefined,
    deviceName: undefined,
    nickname: undefined,
    serialNumber: undefined,
    picUrl: undefined,
    groupIds: undefined,
    roomId: undefined,
    productKey: undefined,
    deviceType: undefined,
    deviceClass: undefined,
    gatewayId: undefined,
    state: undefined,
    keyStatus: undefined,
    wifiLock: undefined,
    keyLock: undefined,
    ssid: undefined,
    onlineTime: undefined,
    offlineTime: undefined,
    activeTime: undefined,
    ip: undefined,
    firmwareId: undefined,
    deviceSecret: undefined,
    mqttClientId: undefined,
    mqttUsername: undefined,
    mqttPassword: undefined,
    authType: undefined,
    latitude: undefined,
    longitude: undefined,
    areaId: undefined,
    address: undefined,
    config: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '设备 ID，主键，自增不能为空', trigger: 'blur' }],
    deviceKey: [{ required: true, message: '设备唯一标识符，全局唯一，用于识别设备不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称，在产品内唯一，用于标识设备不能为空', trigger: 'blur' }],
    roomId: [{ required: true, message: '空间ID不能为空', trigger: 'blur' }],
    deviceType: [{ required: true, message: '设备类型，参见 IotDeviceTypeEnum 枚举不能为空', trigger: 'change' }],
    deviceClass: [{ required: true, message: '设备种类，参见 IotDevicClassEnum 枚举不能为空', trigger: 'change' }],
    state: [{ required: true, message: '设备状态，参见 IotDeviceStateEnum 枚举不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询IoT设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await listIotDevice(queryParams.value);
  iotDeviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询茶室列表 */
const getRoomList = async () => {
  const roomId = route.query && (route.query.roomId as string);
  if(roomId){
    queryParams.value.roomId=roomId
  }
  const res = await listRoomDetails();
  roomDeatails.value = res.rows;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  iotDeviceFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: IotDeviceVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加IoT设备';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: IotDeviceVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getIotDevice(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改IoT设备';
};

/** 提交按钮 */
const submitForm = () => {
  iotDeviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateIotDevice(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addIotDevice(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: IotDeviceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除IoT设备编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delIotDevice(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'tearoom/iotDevice/export',
    {
      ...queryParams.value
    },
    `iotDevice_${new Date().getTime()}.xlsx`
  );
};
/**
 * 获得字典数据的文本展示
 *
 * @param dictType 字典类型
 * @param value 字典数据的值
 * @return 字典名称
 */
const getDictLabel = (options: Array<DictDataOption>, value: any): string => {
  const dictLabel = ref('');
  options.forEach((dict: DictDataOption) => {
    if (dict.value === value + '') {
      dictLabel.value = dict.label;
    }
  });
  return dictLabel.value;
};

/** 设备开关状态修改  */
const handleStatusChange = async (row: IotDeviceVO) => {
  let text = row.keyStatus == 1 ? '合闸' : '关闸';
  try {
    await proxy?.$modal.confirm('确认要"' + text + row.deviceName + '"设备吗?');
    await changeotDeviceStatus(row.id, row.keyStatus);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch (err) {
    row.keyStatus = row.keyStatus == 1 ? 0 : 1;
  }
};

/** 跳转日志分配 */
const handleLog = (row: IotDeviceVO) => {
  const deviceKey = row.deviceKey;
  router.push({path:"/equipment/iotDeviceOperLog",query: {deviceKey:deviceKey}});
};

onMounted(() => {
  getRoomList();
  getList();
});
</script>
